﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace KQ.DCMMP.Common
{
    public static class FileHelper
    {
        public static string GetFileContent(string filePath)
        {
            string content = string.Empty;

            if (!File.Exists(filePath))
            {
                return string.Empty;
            }

            try
            {
                StringBuilder resultBuilder = new StringBuilder();
                using (StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8))
                {
                    string word = reader.ReadLine();
                    while (word != null)
                    {
                        resultBuilder.Append(word.Trim());

                        word = reader.ReadLine();
                    }

                    reader.Close();
                }

                return resultBuilder.ToString();
            }
            catch (Exception ex)
            {
                return string.Empty;
            }

            return content;
        }

        public static List<string> GetFileContents(string filePath)
        {
            List<string> contents = new List<string>();
            string content = string.Empty;

            if (!File.Exists(filePath))
            {
                return contents;
            }

            try
            {
                StringBuilder resultBuilder = new StringBuilder();
                using (StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8))
                {
                    string word = reader.ReadLine();
                    while (word != null)
                    {
                        word = word.Trim();
                        if (!contents.Contains(word))
                        {
                            contents.Add(word);
                        }

                        word = reader.ReadLine();
                    }

                    reader.Close();
                }

                return contents;
            }
            catch (Exception ex)
            {
                return contents;
            }
        }

        public static void WriteFileContent(string filePath, string content, bool append = true)
        {
            try
            {
                using (FileStream fs = new FileStream(filePath, append ? FileMode.Append : FileMode.Create))
                {
                    using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                    {
                        sw.Write(content);
                        sw.Close();
                    }

                    fs.Close();
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}
